#### Figure S1: Affective Polarization Descriptives ####

# Libraries
# library(here)
# library(rio)
# library(tidyverse)
# library(ggthemes)
# library(srvyr)
# library(patchwork)
# library(lubridate)

# data_pnas = import(here("Data","data_pnas.rds"))
# source(here("Code","Functions","funcs_theme.R"))


#### Cross-sectional differences in means ####

cs_affpol = data_pnas |> 
  filter(pid %in% c("Democrat","Republican")) |> 
  select(pid, affpol, outparty, uid, weight) |> 
  pivot_longer(affpol:outparty, names_to = "var", values_to = "val") |> 
  as_survey_design(ids = uid, weights = weight) |> # pivot_longer unsupported for svy-objects
  group_by(pid, var) |> 
  summarise(mean_val = survey_mean(val, na.rm = T, vartype = "ci")) |> 
  ungroup() |> 
  mutate(var = recode(var,
                      outparty = "Out-Party\nAffect",
                      affpol = "Affective\nPolarization"))

# Plot: Difference in Means
p_cs_diff = cs_affpol |> 
  ggplot(aes(x = mean_val,
             y = reorder(var, mean_val),
             group = pid,
             label = round(mean_val, 1),
             shape = var)) +
  geom_pointrange(aes(xmin = mean_val_low,
                      xmax = mean_val_upp,
                      color = pid),
                  position = position_dodge(.3)) +
  geom_text(aes(x = mean_val + 9),
            position = position_dodge(.3)) +
  scale_color_manual(name = "Party",
                     values = c("blue","red")) +
  scale_shape_discrete(name = "Measure") +
  lims(x = c(0,100)) +
  labs(subtitle = "Cross-Sectional Differences",
       x = "Average Values",
       y = NULL) +
  theme_prl() +
  theme(legend.position = "none")

# Sig Test
cs_affpol_sig = data_pnas |> 
  filter(pid %in% c("Democrat","Republican")) |> 
  select(pid, affpol, outparty, uid, weight) |> 
  pivot_longer(affpol:outparty, names_to = "var", values_to = "val") |> 
  group_by(var) |>
  nest() |> 
  mutate(mod = map(data, \(x){
    data_svy = as_survey_design(x, ids =uid, weights = weight)
    svyglm(val ~ pid, design = data_svy)
  })) |> 
  ungroup() |> 
  select(-data)

stargazer(pull(cs_affpol_sig, mod),
          title = "Affective Polarization: Party Differences",
          covariate.labels = c("Republican"),
          column.labels = c("affpol","outparty"),
          notes = "Estimated with survey weights and two-sided tests",
          star.cutoffs = c(0.05, 0.01, 0.001),
          omit.stat = c("aic","bic"),
          ci = T,
          type = "latex",
          out = here("Tables","Supplementary","table_s7.tex"),
          header = F)

rm(cs_affpol_sig)

#### Over-Time differences in means ####

ot_affpol = data_pnas |> 
  filter(pid %in% c("Democrat","Republican")) |> 
  mutate(date = my(format(date, "%b %Y")),
         weight = weight * wt_adj) |>
  select(pid, date, affpol, outparty, weight) |> 
  pivot_longer(affpol:outparty, names_to = "var", values_to = "val") |> 
  as_survey_design(weights = weight) |> # pivot_longer unsupported for svy-objects
  group_by(pid, date, var) |>
  summarise(mean_val = survey_mean(val, na.rm = T, vartype = "ci")) |> 
  ungroup() |> 
  mutate(var = recode(var,
                      outparty = "Out-Party\nAffect",
                      affpol = "Affective\nPolarization"))

p_ot_affpol = ot_affpol |> 
  ggplot(aes(x = date,
             y = mean_val,
             color = pid,
             shape = var)) +
  geom_pointrange(aes(ymin = mean_val_low,
                      ymax = mean_val_upp),
                  position = position_dodge(8)) +
  scale_color_manual(name = "Party",
                     values = c("blue","red")) +
  scale_shape_discrete(name = "Measure") +
  scale_x_date(date_labels = "%b %Y",
               date_breaks = "1 month") +
  lims(y = c(0,100)) +
  labs(subtitle = "Over-Time Differences",
       x = NULL,
       y = "Average Value") +
  theme_prl() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1)) 

# Combined
fig_s1 = (p_cs_diff + plot_layout(guides = "collect") & theme(legend.position = "bottom")) +
  (p_ot_affpol + theme(legend.position = "none")) +
  plot_annotation(caption = "95% Confidence Intervals")

print(fig_s1)

ggsave(here("Plots","Supplementary","figure_s1.png"),
       fig_s1,
       units = "in",
       width = 9, height = 4,
       dpi = 600)

#### Max Difference (In-text mention) ####

maxdiff_out = ot_affpol |> 
  select(pid, date, var, mean_val) |> 
  pivot_wider(id_cols = c("pid","date"), names_from = var, values_from = mean_val) |> 
  group_by(date) |> 
  summarise(across(contains("\n"), ~ abs(max(.x) - min(.x)))) |> 
  arrange(desc(`Out-Party\nAffect`)) |> 
  pull(`Out-Party\nAffect`)

cat("Max monthly difference in out-party affect:",round(max(maxdiff_out),1))